package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;

import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Dragon
 * @since 2021-07-29
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    RedisTemplate redisTemplate;


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("importData finished");
    }

    @Override
    public List<ExcelDictDTO> listExcel() {
        List<Dict> dicts = baseMapper.selectList(null);
        ArrayList<ExcelDictDTO> dictDTOS = new ArrayList<>(dicts.size());
         dicts.forEach(dict -> {
             ExcelDictDTO excelDictDTO = new ExcelDictDTO();
             BeanUtils.copyProperties(dict,excelDictDTO);
             dictDTOS.add(excelDictDTO);
         });
          return  dictDTOS;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        try {
            //先判断redis里面有没有数据
            List<Dict> dictList= (List<Dict>) redisTemplate.opsForValue().get("srb:core:dataList:"+parentId);
            if (dictList!=null){
                log.info("从Redis中获取列表");
                return  dictList;
            }

            //如果有则返回，没有则查询数据库
        } catch (Exception e) {
          log.error("redis服务器异常"+ ExceptionUtils.getStackTrace(e));
        }

        QueryWrapper<Dict> QueryWrapper = new QueryWrapper<Dict>();
        QueryWrapper.eq("parent_id",parentId);
        List<Dict> dicts = baseMapper.selectList(QueryWrapper);
        dicts.forEach(dict -> {
            boolean b = hasChildren(parentId);
            dict.setHasChildren(b);
        });
        try {
            log.info("将数据存入Redis");
            redisTemplate.opsForValue().set("srb:core:dataList:"+parentId,dicts,5, TimeUnit.MINUTES);
            //将查询到的数据放入Redis，然后再返回
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dicts;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> Wrapper = new QueryWrapper<>();
        Wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(Wrapper);

        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> QueryWrapper = new QueryWrapper<>();

          QueryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(QueryWrapper);
        if (dict==null) {
            return "";
        }
        QueryWrapper= new QueryWrapper<>();
         QueryWrapper.eq("parent_id",dict.getId()).eq("value",value);
        Dict newDict = baseMapper.selectOne(QueryWrapper);
         if (dict==null){
             return "";
         }
        return newDict.getName();

    }

    private boolean hasChildren(Long id){
        QueryWrapper<Dict> QueryWrapper = new QueryWrapper<Dict>();
             QueryWrapper.eq("parent_id",id);
        Integer integer = baseMapper.selectCount(QueryWrapper);
        if (integer.intValue()>0) {
            return  true;
        }


     return false;
    }
}
